#=============================================================================#
#
# PROJECT:        Who Pays for Peace?
# AUTHORS:        ** anonymized for review **
# CONTACT:        ** anonymized for review **
# LAST MODIFIED:  May 16, 2023
# 
#=============================================================================#
#
# This R file contains the code used to replicate the average treatment effects 
# (at Wave 2)
# 
#=============================================================================#


# Initial settings ------------------------------------------------------------

#rm(list=ls())
#getwd()

## Install and load all necessary packages ------------------------------------
# ipak function: install and load multiple R packages.
# check to see if packages are installed. Install them if they are not, then load them into the R session.

ipak <- function(pkg){  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if(length(new.pkg)) install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}

packages <- c("stargazer", "pwr", "effectsize") 
ipak(packages)


## Load the data --------------------------------------------------------------
mydata.t2 <- readRDS("data/T2-clean-data.rds")


# ATEs: OLS regressions -------------------------------------------------------
mydata.t2$cost_condition <- mydata.t2$cost1_condition
levels(mydata.t2$cost_condition) <- c("300", "450", "600")
summary(mydata.t2$cost_condition)

## PROVISION 1: Route 1 (r1) --------------------------------------------------
lm_cost1 <- lm(cost1 ~ cost_condition, data = mydata.t2)
lm_cost1_ingroup <- lm(cost1 ~ cost_condition, 
                       data = mydata.t2[mydata.t2$route_1_condition=="Azerbaijan",])

## PROVISION 2: Route 2 (r1) --------------------------------------------------
lm_cost2 <- lm(cost2 ~ cost_condition, data = mydata.t2)
lm_cost2_ingroup <- lm(cost2 ~ cost_condition, 
                       data = mydata.t2[mydata.t2$route_2_condition=="Azerbaijan",])

## Table ----------------------------------------------------------------------
stargazer(lm_cost1, lm_cost1_ingroup, lm_cost2, lm_cost2_ingroup,
          title = "Average Treatment Effects for New Peace Provisions at Wave 2.",
          model.numbers = F,
          ci = T,
          omit.stat = c("ser", "f"),
          star.char = c("*", "**", "***"), 
          star.cutoffs = c(.05, .01, .001),
          notes = c("Cell entries are unstandardized OLS coefficients with confidence intervals (CIs) in parentheses. * p<0.05; ** p<0.01; *** p<0.001 (two-tailed)"),
          align = TRUE, notes.align = "l", notes.append = F,
          out = "tables/table4.txt")


## POSTHOC POWER CALCULATIONS
summary(lm_cost1)
effectsize(lm_cost1)
pwr.r.test(n = NULL, r = 0.16, sig.level = 0.05, power = .85)
